<?php

namespace frontend\controllers;

use app\models\Child\TPatientInfo;
use Yii;
use yii\web\Controller;
use common\help\tools;
use common\help\uploadfile;
use common\help\message;
use yii\helpers\Url;
use app\models\Child\InitAdvert;
use app\models\Child\TSubclinicInfo;
use app\models\Child\SysUserInfo;
use app\models\Child\TReplyInfo;
use app\models\Child\TUserInfo;
use app\models\Child\TOrderInfo;
use app\models\Child\TBookingInfo;
use app\models\Child\TCardUsrRel;
use app\models\Child\TCouponUsrRel;
use app\models\Child\TOrderGoodsDetail;
use app\models\Child\TOrderServiceDetail;
use app\models\Child\AccountUserInfo;
use app\models\Child\UserCode;
use app\models\Child\TOffInfo;
use app\models\Child\InitHomeNursingInfo;
use app\models\Child\TUserNersingRel;
use app\models\Child\InitDiseaseInfo;
use app\models\Child\TUserDiseaseRel;

class ChildController extends Controller {
    
    public $enableCsrfValidation = false;
    
    /*
     * 测试接口文件是否可以正常使用
     * Child控制器下Index方法
     * 访问路径为http://testxrtn.ggling.com/children/frontend/web/index.php?r=child/index
     */

    public function actionIndex()
    {

        echo 1;
        
    }
    
    /*
     * 获取轮播图和广播
     * 接口地址：http://testxrtn.ggling.com/children/frontend/web/index.php?r=child/getadvert
     * 参数：
     *      分店ID：subclinic_id
     *      类型  ：ad_type
     */
    public function actionGetadvert()
    {
        
        /*
         * 接值
         * subclinic_id为分店ID（值为0时表示为首页）
         * ad_type为类型（0轮播图，1广播）
         */
        $subclinic_id = Yii::$app->request->get("subclinic_id");
        $ad_type = Yii::$app->request->get("ad_type");
        /*
         * 实例化轮播图和广播的model层
         */
        $advert = new InitAdvert();
        /*
         * 调用model层中查询轮播图和广播的方法
         */
        $list = $advert->getAdvertList($subclinic_id,$ad_type);
        /*
         * 判断数据库获取到的数据是否为空
         * 若不为空则成功，反之失败
         */
        if(!empty($list))
        {
            /*
             * 获取轮播图信息成功
             */
            $res['code'] = 1;
            $res['info'] = "获取轮播图和广播成功";
            $res['data'] = $list;
        }else{
            /*
             * 获取轮播图信息失败
             */
            $res['code'] = 0;
            $res['info'] = "暂无数据";
            $res['data'] = array();
        }

        return json_encode($res);
        
    }

    /*
     * 获取更多分店
     * 接口地址：http://testxrtn.ggling.com/children/frontend/web/index.php?r=child/getsubclinic
     * 参数：
     *      纬度:lat
     *      经度:lng
     *      分店ID：subclinic_id
     */
    public function actionGetsubclinic()
    {

        /*
         * 接值
         * lat_lon为用户的经纬度
         */
        $lat1 = Yii::$app->request->get('lat');
        $lng1 = Yii::$app->request->get('lng');
//	$lat1 = 40.125996;
//	$lng1 = 116.653076;
        $subclinic_id = Yii::$app->request->get('subclinic_id');
//        echo json_encode($lat1.'|'.$lng1);die;
        $sysUserInfo = new SysUserInfo();
        $replyInfo = new TReplyInfo();
        $orderInfo = new TOrderInfo();
        /*
         * 实例化分店model层
         */
        $subclinic = new TSubclinicInfo();

        $typeId = Yii::$app->request->get('typeId');

        /*
         * 调用model层中查询分店列表的方法
         */
        $list = $subclinic->getSubclinicList($subclinic_id);
        /*
         * 判断数据库获取到的数据是否为空
         * 若不为空则成功，反之失败
         */
        if(!empty($list))
        {
            if(!empty($subclinic_id))
            {
                /*
                 * 通过经纬度计算距离（未完成）
                 */
                $lat_lng = $list['subclinic_lat_lon'];
                if(!empty($lat_lng))
                {
                    $subclinic_lat_lng = explode(',',$lat_lng);
                    $lat2 = $subclinic_lat_lng[0];
                    $lng2 = $subclinic_lat_lng[1];
                    if(empty($lat1) || empty($lng1))
                    {
                        $list['distance'] = "未知";
                    }else{
                        $distance = $this->actionGetdistance($lat1, $lng1, $lat2, $lng2);
                        $list['distance'] = $distance;
                    }
                }else{
                    $list['distance'] = "未知";
                }
                if($list['distance'] != "未知")
                {
                    if($list['distance']>1000)
                    {
                        $list['distance'] = round(($list['distance']/1000),2).'km';
                    }else{
                        $list['distance'] = round($list['distance'],2).'m';
                    }
                }
            }else{
                foreach($list as $k => $v)
                {
                    $lat_lng = $v['subclinic_lat_lon'];
                    if(!empty($lat_lng))
                    {
                        $subclinic_lat_lng = explode(',',$lat_lng);
                        $lat2 = $subclinic_lat_lng[0];
                        $lng2 = $subclinic_lat_lng[1];
                        //echo $lat2."-1-".$lng2."-2-";
                        if(empty($lat1) || empty($lng1))
                        {
                            $list[$k]['distance'] = "未知";
                            $list[$k]['min'] = '未知';
                        }else{
                            $distance = $this->actionGetdistance($lat1,$lng1,$lat2,$lng2);
                            $list[$k]['distance'] = $distance;
                            $list[$k]['min'] = round(($distance/40000),2).'km';
                        }
                    }else{
                        $list[$k]['distance'] = "未知";
                    }
                }

                foreach($list as $k => $v)
                {
                    if($v['distance'] != '未知')
                    {
                        if($v['distance']>1000)
                        {
                            $list[$k]['distance'] = round(($v['distance']/1000),2).'km';
                        }else{
                            $list[$k]['distance'] = round($v['distance'],2).'m';
                        }
                    }
                    //员工人员
                    $list[$k]['userCount'] = $sysUserInfo->getUserBySubclinicIdCount($v['subclinic_id']);
                    //订单数
                    $list[$k]['orderCount'] = $orderInfo->getOrderBySubclinicIdCount($v['subclinic_id']);
                    $reply = $replyInfo->getIntegralGroupBySubclinicId($v['subclinic_id']);
                    //echo $v['subclinic_id'].json_encode($reply);
                    $doctorList = $sysUserInfo -> getDoctorList($v['subclinic_id']);
                    //是否空闲
                    if(empty($doctorList)){
                        //否
                        $list[$k]['isIdle'] = 0;
                    }else{
                        //是
                        $list[$k]['isIdle'] = 1;
                    }
                    //评分
                    if(empty($reply[0]['integral_sum'])){
                        //没有评分默认5分
                        $list[$k]['replyRaion'] = 5;
                        //echo $v['subclinic_id'].json_encode($reply);
                    }else{
                        $list[$k]['replyRaion'] = round($reply[0]['integral_sum']/($reply[0]['integral_count']*4),2);

                    }
                }

                $array = array();
                foreach ($list as $key => $row) {
                    $volume[$key]  = $row['distance'];
                    $edition[$key] = $row['replyRaion'];
                }
                if($typeId==1){
                    array_multisort($volume, SORT_ASC, $list);
                }else{
                    array_multisort($edition, SORT_DESC, $list);
                }

            }
            $res['code'] = 1;
            $res['info'] = "获取分店列表成功";
            $res['data'] = $list;
        }else{
            $res['code'] = 0;
            $res['info'] = "暂无数据";
            $res['data'] = array();
        }

        return json_encode($res);

    }
    public function jistime($luc,$sud){
        return $luc/$sud;
    }
    /*
     * 通过经纬度计算距离
     */
    public function actionGetdistance($lat1,$lng1,$lat2,$lng2)
    {
        $earthRadius = 6367000; //approximate radius of earth in meters 
 
        /* 
        Convert these degrees to radians 
        to work with the formula 
        */

        $lat1 = ($lat1 * pi() ) / 180; 
        $lng1 = ($lng1 * pi() ) / 180; 

        $lat2 = ($lat2 * pi() ) / 180; 
        $lng2 = ($lng2 * pi() ) / 180; 

        /* 
        Using the 
        Haversine formula 

        http://en.wikipedia.org/wiki/Haversine_formula 

        calculate the distance 
        */

        $calcLongitude = $lng2 - $lng1; 
        $calcLatitude = $lat2 - $lat1; 
        $stepOne = pow(sin($calcLatitude / 2), 2) + cos($lat1) * cos($lat2) * pow(sin($calcLongitude / 2), 2); 
        $stepTwo = 2 * asin(min(1, sqrt($stepOne))); 
        $calculatedDistance = $earthRadius * $stepTwo; 

//        if($calculatedDistance>=1000)
//        {
//            $distance = round(($calculatedDistance/1000),2).'km';
//        }else{
//            $distance = round($calculatedDistance,2).'m';
//        }
        return $calculatedDistance;
    }

    /*
     * 获取分店内医生列表
     * 接口地址：http://testxrtn.ggling.com/children/frontend/web/index.php?r=child/getdoctor
     * 可选参数：
     *      分店ID：subclinic_id
     *      纬度:lat
     *      经度:lng
     */
    public function actionGetdoctor()
    {

        /*
         * 接值
         * subclinic_id为分店的id
         */
        $subclinic_id = Yii::$app->request->get('subclinic_id');
        $lat1 = Yii::$app->request->get('lat');
        $lng1 = Yii::$app->request->get('lng');
        /*
         * 实例化医生model层
         */
        $doctor = new SysUserInfo();
        /*
         * 调用model层中查询医生列表方法
         */
        $list = $doctor->getDoctorList($subclinic_id);


        /*
         * 判断数据库获取到的数据是否为空
         * 若不为空则成功，反之失败
         */
        if(!empty($list))
        {
            /*
             * 实例化订单model层
             */
            $orders = new TOrderInfo();
            /*
             * 查询所有医生订单量
             */
            $simples = $orders->getSimple();
            /*
             * 实例化评价表
             */
            $replys = new TReplyInfo();
            /*
             * 查询所有医生的评价信息
             */
            $integrals = $replys->getIntegral();
            /*
             * 通过判断医生ID确定每个医生的接单量,评价量，评分值
             */
            foreach($list as $k => $v)
            {
                $list[$k]['simple'] = 0;
                $list[$k]['integral_count'] = 0;
                $list[$k]['integral_ave'] = 0;
                $list[$k]['integral_star'] = 0;
                foreach($simples as $k1 => $v1)
                {
                    if($v['user_id'] == $v1['doctor_id'])
                    {
                        //订单数
                        $list[$k]['simple'] = $v1['simple'];
                    }
                }
                foreach($integrals as $k2 => $v2)
                {
                    if($v['user_id'] == $v2['doctor_id'])
                    {
                        if(!empty($v2['integral_sum'])){
                            $list[$k]['integral_count'] = $v2['integral_count'];
                            $list[$k]['integral_ave'] = round($v2['integral_sum']/$v2['integral_count'],2);
                            $list[$k]['integral_star'] = round($v2['integral_sum']/$v2['integral_count']);
                        }else{
                            $list[$k]['integral_count'] = 0;
                            $list[$k]['integral_ave'] = 5;
                            $list[$k]['integral_star'] = 5;
                        }
                    }
                }
            }
            foreach($list as $value)
            {
                $array[] = $value['integral_star'];
            }
            array_multisort($array,SORT_DESC,$list);
            /*
             * 判断
             * 如果分店ID为空，调用二维数组去重方法，取出各分店ID对应的第一条数据,其余的移除
             */
            if(empty($subclinic_id))
            {
                /*
                 * 实例化公共方法类
                 */
                $tools = new tools();
                /*
                 * 调用公共方法类中的二维数组去重方法
                 */
                $list = $tools->array_unset_tt($list, 'subclinic_id');
            }
            $list = array_values($list);
            if(empty($subclinic_id))
            {
                foreach($list as $k => $v)
                {
                    $lat_lng = $v['subclinic_lat_lon'];
                    if(!empty($lat_lng))
                    {
                        $subclinic_lat_lng = explode(',',$lat_lng);
                        $lat2 = $subclinic_lat_lng[0];
                        $lng2 = $subclinic_lat_lng[1];

                        if(empty($lat1) || empty($lng1))
                        {
                            $list[$k]['distance'] = "未知";
                        }else{
                            $distance = $this->actionGetdistance($lat1,$lng1,$lat2,$lng2);
                            $list[$k]['distance'] = $distance;
                        }
                    }else{
                        $list[$k]['distance'] = "未知";
                    }
                }
                foreach($list as $k => $v)
                {
                    if($v['distance'] != '未知')
                    {
                        if($v['distance']>1000)
                        {
                            $list[$k]['distance'] = round(($v['distance']/1000),2).'km';
                        }else{
                            $list[$k]['distance'] = round($v['distance'],2).'m';
                        }
                    }
                }
            }
            $res['code'] = 1;
            $res['info'] = "更多技师列表成功";
            $res['data'] = $list;
        }else{
            $res['code'] = 0;
            $res['info'] = "暂无数据";
            $res['data'] = array();
        }

        return json_encode($res);

    }
    
    /*
     * 获取全部医生列表
     * 接口地址：http://testxrtn.ggling.com/children/frontend/web/index.php?r=child/getalldoctor
     * 可选参数：
     *      纬度:lat
     *      经度:lng
     */
    public function actionGetalldoctor()
    {
        
        /*
         * 接值
         */
	$subclinic_id = '';
        $lat1 = Yii::$app->request->get('lat');
        $lng1 = Yii::$app->request->get('lng');
        /*
         * 实例化医生model层
         */
        $doctor = new SysUserInfo();
        /*
         * 调用model层中查询医生列表方法
         */
        $list = $doctor->getDoctorList($subclinic_id);
        
        
        /*
         * 判断数据库获取到的数据是否为空
         * 若不为空则成功，反之失败
         */
        if(!empty($list))
        {
            /*
             * 实例化订单model层
             */
            $orders = new TOrderInfo();
            /*
             * 查询所有医生订单量
             */
            $simples = $orders->getSimple();
            /*
             * 实例化评价表
             */
            $replys = new TReplyInfo();
            /*
             * 查询所有医生的评价信息
             */
            $integrals = $replys->getIntegral();
            /*
             * 通过判断医生ID确定每个医生的接单量,评价量，评分值
             */
            foreach($list as $k => $v)
            {
                $list[$k]['simple'] = 0;
                $list[$k]['integral_count'] = 0;
                $list[$k]['integral_ave'] = 0;
                $list[$k]['integral_star'] = 0;
                foreach($simples as $k1 => $v1)
                {
                    if($v['user_id'] == $v1['doctor_id'])
                    {
                        $list[$k]['simple'] = $v1['simple'];
                    }
                }
                foreach($integrals as $k2 => $v2)
                {
                    if($v['user_id'] == $v2['doctor_id'])
                    {
                        $list[$k]['integral_count'] = $v2['integral_count'];
                        $list[$k]['integral_ave'] = round($v2['integral_sum']/$v2['integral_count'],2);
                        $list[$k]['integral_star'] = round($v2['integral_sum']/$v2['integral_count']);
                    }
                }
            }
            foreach($list as $value)
            {
                $array[] = $value['integral_star'];
            }
            array_multisort($array,SORT_DESC,$list);
            $list = array_values($list);
            if(empty($subclinic_id))
            {
                foreach($list as $k => $v)
                {
                    $lat_lng = $v['subclinic_lat_lon'];
                    if(!empty($lat_lng))
                    {
                        $subclinic_lat_lng = explode(',',$lat_lng);
                        $lat2 = $subclinic_lat_lng[0];
                        $lng2 = $subclinic_lat_lng[1];
                        
                        if(empty($lat1) || empty($lng1))
                        {
                            $list[$k]['distance'] = "未知";
                        }else{
                            $distance = $this->actionGetdistance($lat1,$lng1,$lat2,$lng2);
                            $list[$k]['distance'] = $distance;
                        }
                    }else{
                        $list[$k]['distance'] = "未知";
                    }
                }
                $array = array();
                foreach($list as $k => $v)
                {
                    if($v['distance'] != '未知')
                    {
                        if($v['distance']>1000)
                        {
                            $list[$k]['distance'] = round(($v['distance']/1000),2).'km';
                        }else{
                            $list[$k]['distance'] = round($v['distance'],2).'m';
                        }
                    }
                }
            }
            $res['code'] = 1;
            $res['info'] = "更多技师列表成功";
            $res['data'] = $list;
        }else{
            $res['code'] = 0;
            $res['info'] = "暂无数据";
            $res['data'] = array();
        }

        return json_encode($res);
        
    }
    
    /*
     * 获取需要评价的服务列表
     * 接口地址：http://testxrtn.ggling.com/children/frontend/web/index.php?r=child/getservice
     * 参数：
     *      预约ID：booking_id
     */
    public function actionGetservice()
    {
        
        /*
         * 接值
         */
        $booking_id = Yii::$app->request->get('booking_id');
        /*
         * 实例化订单表model层
         */
        $services = new TOrderInfo();
        /*
         * 调用model层中需要评价的服务列表
         */
        $list = $services->orderList($booking_id);
        
        if(!empty($list))
        {
            $res['code'] = 1;
            $res['info'] = "获取需评价的服务列表成功";
            $res['data'] = $list;
        }else{
            $res['code'] = 0;
            $res['info'] = "暂无数据";
            $res['data'] = array();
        }
        
        return json_encode($res);
        
    }
    
    /*
     * 对医生的服务进行评价
     * 接口地址：http://testxrtn.ggling.com/children/frontend/web/index.php?r=child/setreply
     * 参数：
     *      订单号：booking_id
     *      医生ID：doctor_id
     *      用户ID：user_id
     *      用户名：user_name
     *      评分值：reply_integral
     *      评价内容：reply_info
     */
    public function actionSetreply()
    {
        
        /*
         * 接值
         */
        $booking_id = Yii::$app->request->post('booking_id');
        $doctor_id = Yii::$app->request->post('doctor_id');
        $user_id = Yii::$app->request->post('user_id');
        $user_name = Yii::$app->request->post('user_name');
        $reply_integral = Yii::$app->request->post('reply_integral');
        $reply_info = Yii::$app->request->post('reply_info');
        
//        $data = Yii::$app->request->post('datas');
        //$data = array(array('order_no' => '3221p3E685177019eypadRl630BT','doctor_id' => 1,'user_id'=>1,'user_name' => '一叶知秋','reply_integral'=>2,'reply_info'=>'222'),array('order_no' => '3221p3E685177019eypadRl630u41V','doctor_id' => 1,'user_id'=>1,'user_name' => '一叶知秋2222','reply_integral'=>2,'reply_info'=>'222'));
        /*
         * 定义变量time为当前时间
         */
        $time = date('Y-m-d H:i:s',time());
        /*
         * 通过预约id拿到booking_id
         */
        $orders = new TOrderInfo();
        $list = $orders->getOrderId($booking_id);
        $order_id = $list['order_id'];
        /*
         * 实例化服务评价model
         */
        $reply = new TReplyInfo();
        $lists = $reply->getList($booking_id);
        if(!empty($lists))
        {
            /*
             * 调用model层中评价服务的方法
             */
    //        $result = $reply->setReply($order_id,$doctor_id,$user_id,$user_name,$reply_integral,$reply_info,$time);
            /*
             * 开启mysql事务处理，只有所有评价全部插入数据库成功才会提交，否则事务回滚
             */
            $trans = Yii::$app->db->beginTransaction();
            try{
                $result = $reply->setReply($order_id,$doctor_id,$user_id,$user_name,$reply_integral,$reply_info,$time);
                $result1 = $orders->setStatus($order_id);
                if(!$result || !$result1)
                {
                    $trans->rollback();
                    $res['code'] = 0;
                    $res['info'] = "评价失败，请稍后重试";
                    return json_encode($res);
                }
                $res['code'] = 1;
                $res['info'] = "评价服务成功";
                $trans->commit();
            } catch (Exception $ex) {
                $trans->rollback();
                $res['code'] = 0;
                $res['info'] = "评价失败，请稍后重试";
            }
        }else{
            $res['code'] = 2;
            $res['info'] = "您已对本次服务进行过评价";
        }
//        $trans = Yii::$app->db->beginTransaction();
//        try{
//            foreach($data as $v)
//            {
//                $replys = clone $reply;
//                $result = $replys->setReply($v);
//                if(!$result)
//                {
//                    $trans->rollback();
//                    $res['code'] = 0;
//                    $res['info'] = "评价失败，请稍后重试";
//                    return json_encode($res);
//                }
//            }
//            $res['code'] = 1;
//            $res['info'] = "评价服务成功";
//            $trans->commit();
//        } catch (Exception $e) {
//            $trans->rollback();
//            $res['code'] = 0;
//            $res['info'] = "评价失败，请稍后重试";
//        }
        /*
         * 判断向数据库中插入评价信息结果是否为true
         * 若为true则成功，反之失败
         */
//        if($result)
//        {
//            /*
//             * 修改订单评价状态
//             */
//            $result1 = $orders->setStatus($order_id);
//            if($result1)
//            {
//                $res['code'] = 1;
//                $res['info'] = "评价该次服务已成功";
//            }else{
//                $res['code'] = 1;
//                $res['info'] = "评价成功，但状态未修改";
//            }
//        }else{
//            $res['code'] = 0;
//            $res['info'] = "评价失败，请稍后重试";
//        }
        
        return json_encode($res);
        
    }
    
    /*
     * 会员资料设置
     * 接口地址：http://testxrtn.ggling.com/children/frontend/web/index.php?r=child/setuser
     * 参数：
     *      用户ID：user_id
     *      用户头像：file
     *      用户姓名：user_name
     *      用户性别：user_gender(0男 1女)
     *      用户生日：user_birthday
     */
    public function actionSetuser()
    {
        
        /*
         * 接值
         */
        $user_id = Yii::$app->request->post('user_id');
//        $file = $_FILES;
        $user_name = Yii::$app->request->post('user_name');
        $user_gender = Yii::$app->request->post('user_gender');
        $user_birthday = Yii::$app->request->post('user_birthday');
        $user_img = Yii::$app->request->post('user_img');
        $width = Yii::$app->request->post('width');
        $height = Yii::$app->request->post('height');
        /*
         * 若姓名为空，则不运行上传
         */
        if(!empty($user_name))
        {
            /*
             * 若头像不为空，则需要实例化上传model，并调用图片上传方法，得到图片存储路径(未完成)
            */
//            if(!empty($file))
//            {
//                if(!empty($file['file']['name']))
//                {
//                    $save_path = "uploads/img/".date('Y-m-d');
//                    $file_name = mt_rand();
//                    $config = array(
//                            'savePath' => $save_path,
//                            'fileName' => $file_name
//                    );
//                    $obj = new uploadfile($config);
//                    $url = $obj->upload($file,$save_path,$file_name);
//                    $user_img = Url::to('@web/',true).$url;
//                }
//            }
            /*
            * 实例化会员model
            */
           $users = new TUserInfo();
           /*
            * 调用model层中的设置资料方法
            */
           $result = $users->setUserInfo($user_id,$user_img,$user_name,$user_gender,$user_birthday,$width,$height);
           /*
            * 判断向数据库中修改会员资料结果是否为true
            * 若为true则成功，反之失败
            */
           if($result)
           {
               $res['code'] = 1;
               $res['info'] = "会员资料设置成功";
           }else{
               $res['code'] = 0;
               $res['info'] = "设置失败，请稍后重试";
           }
        }else{
            $res['code'] = 2;
            $res['info'] = "姓名不能为空";
        }
        
        return json_encode($res);
        
    }
    
    /*
            文件上传
     */
    function upload_file()
    {
            $file = $_FILES;
            $save_path = "uploads/".$dir."/img/".date('Y-m-d');
            $file_name = mt_rand();
            $config = array(
                    'savePath' => $save_path,
                    'fileName' => $file_name
            );
            $obj = new UploadFile($config);
            $url = $obj->upload($file,$save_path,$file_name);
            $url = "http://".base_url().$url;
            if($url)
            {
                    $res['code'] = 0;
                    $res['info'] = "文件上传成功";
                    $res['url'] = $url;
            }else{
                    $res['code'] = 1;
                    $res['info'] = "文件上传失败";
            }

            echo json_encode($res);

    }
    
    /*
     * 获取会员中心个人资料部分
     * 接口地址：http://testxrtn.ggling.com/children/frontend/web/index.php?r=child/getuser
     * 参数：
     *      用户ID：user_id
     */
    public function actionGetuser()
    {
        
        /*
         * 接值
         */
        $user_id = Yii::$app->request->get('user_id');
        /*
         * 实例化用户model层、用户与次卡关系model层、用户与优惠卷关系model层
         */
        $users = new TUserInfo();
        $cards = new TCardUsrRel();
        $coupons = new TCouponUsrRel();
        /*
         * 调用用户model层中获取用户资料的方法
         */
        $list = $users->getUserList($user_id);
        if($list['user_img'] == '')
        {
            $list['user_img'] = 'http://testxrtn.ggling.com/children/frontend/web/uploads/img/2018-03-14/20180314172404.png';
        }
        /*
         * 调用用户与次卡关系model层中获取用户剩余次卡总次数的方法
         */
        $list['cards'] = $cards->getCardCount($user_id);
        /*
         * 调用用户与优惠卷关系model层中获取用户剩余优惠卷总数量的方法
         */
        $list['coupons'] = $coupons->getCouponsCount($user_id);
        /*
         * 判断数据库获取到的数据是否为空
         * 若不为空则成功，反之失败
         */
        if(!empty($list))
        {
            $res['code'] = 1;
            $res['info'] = "获取会员资料成功";
            $res['data'] = $list;
        }else{
            $res['code'] = 0;
            $res['info'] = "暂无数据";
            $res['data'] = array();
        }
        
        return json_encode($res);
        
    }
    
    /*
     * 获取会员中心预约列表（包括已预约，已完成，已取消三种状态）
     * 接口地址：http://testxrtn.ggling.com/children/frontend/web/index.php?r=child/getbooking
     * 参数：
     *      用户ID：user_id
     */
    public function actionGetbooking()
    {
        
        /*
         * 接值
         */
        $user_id = Yii::$app->request->get('user_id');
        /*
         * 实例化预约表model层
         */
        $booking = new TBookingInfo();
        /*
         * 调用预约表model层中获取预约列表的方法
         */
        $list = $booking->getBookingList($user_id);
        /*
         * 判断数据库获取到的数据是否为空(订单状态为4是完成，为5是已取消，其他均为已预约)
         * 若不为空则成功，反之失败
         */
        if(!empty($list))
        {
//            foreach($list as $k => $v)
//            {
//                if($v['order_state'] == 0)
//                {
//                    $arr['be_done'][] = $v;
//                }else if($v['order_state'] == 4){
//                    $arr['be_cancel'][] = $v;
//                }else{
//                    $arr['be_speak'][] = $v;
//                }
//            }
            foreach($list as $k => $v)
            {
                if($v['booking_status'] == 4)
                {
                    /*
                     * 已完成
                     */
                    $list[$k]['status'] = 1;
                }else if($v['booking_status'] == 5)
                {
                    /*
                     * 已取消
                     */
                    $list[$k]['status'] = 2;
                }else{
                    /*
                     * 已预约
                     */
                    $list[$k]['status'] = 0;
                }
            }
            $res['code'] = 1;
            $res['info'] = "获取预约列表成功";
            $res['data'] = $list;
        }else{
            $res['code'] = 0;
            $res['info'] = "暂无数据";
            $res['data'] = array();
        }
        
        return json_encode($res);
        
    }
    
    /*
     * 订单详情
     * 接口地址：http://testxrtn.ggling.com/children/frontend/web/index.php?r=child/orderinfo
     * 参数：
     *      预约ID：booking_id
     */
    public function actionOrderinfo()
    {
        /*
         * 接值
         */
        $booking_id = Yii::$app->request->get('booking_id');
         /*
         * 实例化订单表model层
         */
        $orders = new TOrderInfo();
        /*
         * 调用model中订单详情方法
         */
        $list = $orders->getOrderInfo($booking_id);
        
        if(!empty($list))
        {
            /*
             * 实例化商品详情表model层
             */
            $goods = new TOrderGoodsDetail();
            $list1 = $goods->TOrderGoods($list['order_id']);
            /*
             * 实例化推拿服务详情表model层
             */
            $services = new TOrderServiceDetail();
            $list2 = $services->TOrderService($list['order_id']);

            $list['goods'] = array();
            $list['service'] = array();
            $list['sum'] = 0;
            if(is_array($list1) && !empty($list1))
            {
                $list['goods'] = $list1;
                foreach($list1 as $k1 => $v1)
                {
                    $list['sum'] += $v1['goods_sum_cost'];
                }
            }
            if(is_array($list2) && !empty($list2))
            {
                $list['service'] = $list2;
                foreach($list2 as $k2 => $v2)
                {
                    $list['sum'] += $v2['service_sum_cost'];
                }
            }
            $res['code'] = 1;
            $res['info'] = "获取订单详情成功";
            $res['data'] = $list;
        }else{
            $res['code'] = 0;
            $res['info'] = "暂无该订单信息";
            $res['data'] = array();
        }

        return json_encode($res);
        
    }
    
    /*
     * 预约医生
     * 接口地址：http://testxrtn.ggling.com/children/frontend/web/index.php?r=child/setbooking
     * 参数：
     *      门店ID：subclinic_id
     *      用户ID：user_id
     *      用户姓名：user_name
     *      用户性别：user_gender(0男 1女)
     *      联系电话：user_phone
     *      医生ID：doctor_id
     *      预约时间：booking_time
     */
    public function actionSetbooking()
    {
        
        /*
         * 接值
         */
        $subclinic_id = Yii::$app->request->post('subclinic_id');  //分店ID
        $user_id = Yii::$app->request->post('user_id');   //用户ID
        $user_name = Yii::$app->request->post('user_name');  // 用户姓名
        $user_gender = Yii::$app->request->post('user_gender');
        $user_phone = Yii::$app->request->post('user_phone');
        $doctor_id = Yii::$app->request->post('doctor_id');   //一声ID
        $booking_time = Yii::$app->request->post('booking_time');  //预约时间
        // $subclinic_id = 1;
        // $user_id=71;
        // $doctor_id=1;
        // $booking_time='2018-04-16 12:11:22';
        $length = 4;
        $str = $this->getRandomString($length);
        $booking_no = 'GYT'.date('Ymd').'00100'.$str;
        $create_time = date('Y-m-d H:i:s',time());
        $time = time();
	$booking = explode(' ',$booking_time);
        if($time - strtotime($booking_time) > 1800)
        {
            $res['code'] = 5;
            $res['info'] = "您预约的时间段不可预约";
        }else{
            if(empty($subclinic_id) || empty($user_id))
            {
                $res['code'] = 4;
                $res['info'] = "预约信息不全，请补全信息后重新预约";
            }else{
		if(!empty($booking_time))
		{
		    $booking = explode(' ',$booking_time);
		    $bookings = explode('-',$booking[0]);
		    if($bookings[1] < 10)
		    {
			$bookings[1] = '0'.$bookings[1];
		    }
		    if($bookings[2] < 10)
		    {
			$bookings[2] = '0'.$bookings[2];
		    }
		    $booking_times = $bookings[0].'-'.$bookings[1].'-'.$bookings[2];
		    /*
		     *	根据医生ID以及日期判断医生是否请假
		     */
		    $off = new TOffInfo();
		    $results = $off->getLists($doctor_id,$booking_times);
		    if($results)
		    {
			$res['code'] = 4;
			$res['info'] = "当前时间段该医生已请假，请选择其他医生";
		    }else{
			/*
			 * 实例化患者预约信息表model层
			 */
			$booking = new TBookingInfo();
            
                                       //查询此人是否预约过
                                       $userinfo = $booking->getBookingList($user_id);
                                       if(empty($userinfo)){
                                               //修改用户表里用户信息所属分店ID
                                               $user = new TUserInfo;
                                               $user->updateUser($user_id,$subclinic_id);
                                       }
			/*
			 * 判断预约的医生在该时间段是否已被预约
			 */
			$list = $booking->getList($doctor_id,$booking_time);
                                            if(!empty($list))
                                            {
                                                if($list['booking_status'] == 5)
                                                {
                                                    $list = array();
                                                }
                                            }
			if(empty($list))
			{
			    $lists = $booking->getLists($user_id,$booking_time);
                                                if(!empty($lists))
                                                {
                                                    if($lists['booking_status'] == 5)
                                                    {
                                                        $lists = array();
                                                    }
                                                }
			    if(empty($lists))
			    {
				/*
				 * 调用患者预约信息表model层中的预约方法
				 */
				$result = $booking->setBooking($booking_no,$subclinic_id,$user_id,$user_name,$user_gender,$user_phone,$doctor_id,$booking_time,$create_time);
				/*
				 * 判断向数据库中预约结果是否为true
				 * 若为true则成功，反之失败
				 */
				if($result)
				{
				    $res['code'] = 1;
				    $res['info'] = "预约医生成功";
				}else{
				    $res['code'] = 0;
				    $res['info'] = "预约失败，请稍后重试";
				}
			    }else{
				$res['code'] = 3;
				$res['info'] = "您已在当前时间段预约其他医生，请先取消之前的预约后再次预约";
			    }
			}else{
			    $res['code'] = 2;
			    $res['info'] = "当前时间段该医生已被预约，请刷新后重试";
			}
		    }
		}
            }
        }
        
        return json_encode($res);
        
    }
    
    /*
     * 生成随机验证码
     */
    public function getRandomString($len, $chars=null)
    {
        if (is_null($chars))
        {
//            $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
	    $chars = "0123456789";
        }  
        mt_srand(10000000*(double)microtime());
        for ($i = 0, $str = '', $lc = strlen($chars)-1; $i < $len; $i++)
        {
            $str .= $chars[mt_rand(0, $lc)];  
        }
        return $str;
    }
    
    /*
     * 医生时间表
     * 接口地址：http://testxrtn.ggling.com/children/frontend/web/index.php?r=child/doctor
     * 参数：
     *      医生ID：doctor_id
     */
    public function actionDoctor()
    {
        
        /*
         * 接值
         */
        $doctor_id = Yii::$app->request->get('doctor_id');
        /*
         * 定义时间区间
         */
        $start_time = strtotime(date('Y-m-d 00:00:00',time()));
        $end_time = strtotime(date('Y-m-d 23:59:59',strtotime("+4 day")));
        $time1 = date('d',time());
        $time2 = date('d',strtotime("+1 day"));
        $time3 = date('d',strtotime("+2 day"));
        $time4 = date('d',strtotime("+3 day"));
        $time5 = date('d',strtotime("+4 day"));
        /*
         * 实例化预约表model层
         */
        $doctors = new TBookingInfo();
        /*
         * 调用model层中查询医生已预约时间方法
         */
        $list = $doctors->getTimes($doctor_id,$start_time,$end_time);
        /*
         * 移除预约状态为取消的时间
         */
        if(!empty($list))
        {
            foreach($list as $k => $v)
            {
                if($v['booking_status'] == 5)
                {
                    unset($list[$k]);
                }
            }
        }
        
        /*
         * 获取医生请假时间
         */
        $off = new TOffInfo();
        $lists = $off->getList($doctor_id);
        $ho = array();
        if(!empty($lists))
        {
            foreach($lists as $k => $v)
            {
                if($v['off_day'] == date('Y-m-d',time()))
                {
                    $ho[] = 0;
                }else if($v['off_day'] == date('Y-m-d',strtotime("+1 day")))
                {
                    $ho[] = 1;
                }else if($v['off_day'] == date('Y-m-d',strtotime("+2 day")))
                {
                    $ho[] = 2;
                }else if($v['off_day'] == date('Y-m-d',strtotime("+3 day")))
                {
                    $ho[] = 3;
                }else if($v['off_day'] == date('Y-m-d',strtotime("+4 day")))
                {
                    $ho[] = 4;
                }
            }
        }
        if(!empty($list))
        {
            $arr = array($time1 => array(),$time2 => array(),$time3 => array(),$time4 => array(),$time5 => array());
            foreach($list as $k => $v)
            {
                if($time1 == date('d', strtotime($v['booking_time'])))
                {
                    $arr[$time1][] = date('H', strtotime($v['booking_time']));
                }else if($time2 == date('d', strtotime($v['booking_time']))){
                    $arr[$time2][] = date('H', strtotime($v['booking_time']));
                }else if($time3 == date('d', strtotime($v['booking_time']))){
                    $arr[$time3][] = date('H', strtotime($v['booking_time']));
                }else if($time4 == date('d', strtotime($v['booking_time']))){
                    $arr[$time4][] = date('H', strtotime($v['booking_time']));
                }else if($time5 == date('d', strtotime($v['booking_time']))){
                    $arr[$time5][] = date('H', strtotime($v['booking_time']));
                }
            }
            $times = array_values($arr);
            
            $res['code'] = 1;
            $res['info'] = "获取医生已预约时间成功";
            $res['data'] = $times;
            $res['ho'] = $ho;
        }else{
            $res['code'] = 0;
            $res['info'] = "该医生暂无预约";
            $res['data'] = array(array(),array(),array(),array(),array());
            $res['ho'] = $ho;
        }

        return json_encode($res);
        
    }
    
    /*
     * 取消预约
     * 接口地址：http://testxrtn.ggling.com/children/frontend/web/index.php?r=child/cancal
     * 参数：
     *      预约ID：booking_id
     */
    public function actionCancal()
    {
        /*
         * 接值
         */
        $booking_id = Yii::$app->request->post('booking_id');
	$cancel_time = date('Y-m-d H:i:s',time());
        /*
         * 查询预约单是否正在治疗中,若正在治疗，不能取消预约
         */
        
        /*
         * 实例化预约表model层
         */
        $bookings = new TBookingInfo();
        /*
         * 调用取消预约接口
         */
        $result = $bookings->removeBooking($booking_id,$cancel_time);
        if($result)
        {
            $res['code'] = 1;
            $res['info'] = "取消预约成功";
        }else{
            $res['code'] = 0;
            $res['info'] = "取消预约失败";
        }
        
        return json_encode($res);
        
    }
    
    /*
     * 通过code换取openid
     * 接口地址：http://testxrtn.ggling.com/children/frontend/web/index.php?r=child/getopenid
     */
    public function actionGetopenid()
    {
        /*
         * 接值
         */
        $code = Yii::$app->request->get('code');
        /*
         * 定义变量
         */
        $appid = 'wx039671590308b129';
        $appsecret = '4e816cd9d4e83306f277ef10fb91b2ce';
        /*
         * 定义url
         */
        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$appid."&secret=".$appsecret."&code=".$code."&grant_type=authorization_code";
        /*
         * 开启curl
         */
        $ch = curl_init();
        /*
         * 设置传输选项及地址
         */
        curl_setopt($ch,CURLOPT_URL,$url);
        /*
         * 以文件流形式返回
         */
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
        /*
         * 发送curl请求
         */
        $arr = curl_exec($ch);
        /*
         * 解除json编码
         */
        $arrs = json_decode($arr,TRUE);
        /*
         * 从中取出access_token和openid
         */
        $access_token = $arrs['access_token'];
        $open_id = $arrs['openid'];
//        echo $open_id;die;
        
        /*
         * 实例化用户类，判断openid在数据库中是否存在
         */
        $users = new TUserInfo();
        /*
         * 调用根据openid查询方法
         */
        $list = $users->getUser($open_id);
        
        
        /*
         * 判断user_id是否存在
         */
        if(!empty($list))
        {
            header("location:http://testxrtn.ggling.com/xetn/sign.html?open_id=".$open_id."&user_id=".$list['user_id']);
        }else{
	    /*
	     * 根据acces_token和open_id获取用户信息
	     */
//	    $urls = "https://api.weixin.qq.com/sns/userinfo?access_token=".$access_token."&openid=".$open_id."&lang=zh_CN";
	    /*
	     * 开启curl
	     */
//	    $ch = curl_init();
	    /*
	     * 设置传输选项及地址
	     */
//	    curl_setopt($ch,CURLOPT_URL,$urls);
	    /*
	     * 以文件流形式返回
	     */
//	    curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
	    /*
	     * 发送curl请求
	     */
//	    $arr1 = curl_exec($ch);
	    /*
	     * 解除json编码
	     */
//	   $array = json_decode($arr1,TRUE);
	   $user_name = 'name';
            header("location:http://testxrtn.ggling.com/xetn/sign.html?open_id=".$open_id."&user_name=".$user_name);
        }
        
    }
    
    /*
     * 获取用户优惠卷信息
     * 接口地址：http://testxrtn.ggling.com/children/frontend/web/index.php?r=child/getcoupon
     * 参数：
     *      用户ID：user_id
     */
    public function actionGetcoupon()
    {
        
        /*
         * 接值
         */
        $user_id = Yii::$app->request->get('user_id');
        /*
         * 实例化优惠卷model层
         */
        $coupon = new TCouponUsrRel();
        /*
         * 调用查询优惠卷列表方法
         */
        $list = $coupon->getList($user_id);
        
        /*
         * 判断列表是否为空
         */
        if(!empty($list))
        {
            foreach($list as $k => $v)
            {
                if($v['subclinic_name'] == '')
                {
                    $list[$k]['subclinic_name'] = "所有门店";
                }
            }
            $res['code'] = 1;
            $res['info'] = "获取用户消费记录列表成功";
            $res['data'] = $list;
        }else{
            $res['code'] = 0;
            $res['info'] = "暂无数据";
            $res['data'] = array();
        }
        
        return json_encode($res);
        
    }
    
    /*
     * 获取用户计次卡剩余次数
     * 接口地址：http://testxrtn.ggling.com/children/frontend/web/index.php?r=child/getcard
     * 参数：
     *      用户ID：user_id
     */
    public function actionGetcard()
    {
        
        /*
         * 接值
         */
        $user_id = Yii::$app->request->get('user_id');
        /*
         * 实例化计次卡类
         */
        $card = new TCardUsrRel();
        /*
         * 调用计次卡剩余列表方法
         */
        $list = $card->getList($user_id);
        
        /*
         * 判断列表是否为空
         */
        if(!empty($list))
        {
            /*
             * 实例化次卡消费记录表
             */
            $account = new AccountUserInfo();
            /*
             * 调用查询列表方法
             */
            $list1 = $account->getList($user_id);
            if(!empty($list1))
            {
                foreach($list1 as $k => $v)
                {
                    if($v['account_type'] == 0)
                    {
                        $list1[$k]['card_name'] = '充值—'.$v['card_name'];
                        $list1[$k]['account_cost'] = '+'.ceil($v['account_cost']);
                    }else{
                        $list1[$k]['card_name'] = '消费—'.$v['card_name'];
                        $list1[$k]['account_cost'] = '-'.ceil($v['account_cost']);
                    }
                }
                $res['code'] = 1;
                $res['info'] = "获取成功";
                $res['count'] = count($list);
                $res['data'] = $list;
                $res['data1'] = $list1;
            }else{
                $res['code'] = 2;
                $res['info'] = "暂无计次卡信息";
                $res['count'] = count($list);
                $res['data'] = $list;
                $res['data1'] = array();
            }
        }else{
            $res['code'] = 0;
            $res['info'] = "暂无数据";
            $res['count'] = 0;
            $res['data'] = array();
            $res['data1'] = array();
        }
        
        return json_encode($res);
        
    }
    
    /*
     * 获取登录短信验证码
     * 接口地址：http://testxrtn.ggling.com/children/frontend/web/index.php?r=child/getcode
     * 参数：
     *      手机号：user_phone
     */
    public function actionGetcode()
    {
        /*
         * 接值
         */
        $user_phone = Yii::$app->request->get('user_phone');
//        $user_phone = '18519518544';
        /*
         * 定义参数
         *      随机数：rand_num
         *      时效性：time
         *      模板ID：temp_id
         *      创建时间：create_time
         */
        $rand_num = rand(100000,999999);
        $create_time = time();
        $temp_id = 238271;
        $time = 5;
        
        /*
         * 发送短信
         */
        $result = $this->actionSendTemplateSMS($user_phone,array($rand_num,$time), $temp_id);
        
        if($result)
        {
            /*
             * 若短信发送成功，则将信息存储数据库里
             */
            $users = new UserCode();
            $result2 = $users->setCode($user_phone,$rand_num,$create_time);
            if($result2)
            {
                $res['code'] = 1;
                $res['info'] = "验证码发送成功";
            }else{
                $res['code'] = 2;
                $res['info'] = "验证码发送成功,但并未保存有效期";
            }
        }else{
            $res['code'] = 0;
            $res['info'] = "发送失败，请稍后重试";
        }
        
        return json_encode($res);
        
}

    /**
     * 发送模板短信
     * @param to 手机号码集合,用英文逗号分开
     * @param datas 内容数据 格式为数组 例如：array('Marry','Alon')，如不需替换请填 null
     * @param $tempId 模板Id
     */       
    public function actionSendTemplateSMS($to,$datas,$tempId)
    {
        
        // 初始化REST SDK
//        global $accountSid,$accountToken,$appId,$serverIP,$serverPort,$softVersion;
         /*
         * 主账号
         */
        $accountSid = "8aaf07086150ec50016154daf25e00f2";
        /*
         * 主账号token
         */
        $accountToken = "42e4ad8eb2464ac39568aacc4e8fd6b2";
        /*
         * 应用id
         */
        $appId = "8aaf07086150ec50016154daf2b500f8";
        /*
         * 请求地址，格式如下
         */
        $serverIP = 'app.cloopen.com';
        /*
         * 请求端口
         */
        $serverPort='8883';
        /*
         * REST版本号
         */
        $softVersion = '2013-12-26';
        
        $rest = new message($serverIP,$serverPort,$softVersion);
        $rest->setAccount($accountSid,$accountToken);
        $rest->setAppId($appId);

        // 发送模板短信
//        echo "Sending TemplateSMS to $to <br/>";
        $result = $rest->sendTemplateSMS($to,$datas,$tempId);
        if($result == NULL )
        {
//            echo "result error!";
//            break;
            return false;
        }
        if($result->statusCode!=0)
        {
//            echo "error code :" . $result->statusCode . "<br>";
//            echo "error msg :" . $result->statusMsg . "<br>";
            return false;
            //TODO 添加错误处理逻辑
        }else{
//            echo "Sendind TemplateSMS success!<br/>";
            // 获取返回信息
//            $smsmessage = $result->TemplateSMS;
//            echo "dateCreated:".$smsmessage->dateCreated."<br/>";
//            echo "smsMessageSid:".$smsmessage->smsMessageSid."<br/>";
            //TODO 添加成功处理逻辑
            return true;
        }
    }
    
    /*
     * 登录
     * 接口地址：http://testxrtn.ggling.com/children/frontend/web/index.php?r=child/login
     * 参数：
     *      手机号：user_phone
     *      验证码：code
     *      openId：open_id
     */
    public function actionLogin()
    {
        /*
         * 接值
         */
        $user_phone = Yii::$app->request->post('user_phone');
        $code = Yii::$app->request->post('code');
        $open_id = Yii::$app->request->post('open_id');
//	$user_name = Yii::$app->request->post('user_name');
        $user_name = $user_phone;

        $connection  = Yii::$app->db;
        $sql     = "select from_id from init_from_info where from_name="."'微信'";
        $command = $connection->createCommand($sql);
        $res     = $command->queryOne();

//        $user_phone = '18519518544';
//        $open_id = '555';
//        $result = 1000;
        /*
	 * 获取用户微信昵称
	 */

        /*
         * 判断手机验证码是否正确
         */
//        $result = $this->actionCheckcode($user_phone,$code);
//        if($result == 1000)
//        {
        /*
         * 若登录成功需要返回user_id
         */
        $user = new TUserInfo();
        $list = $user->getList($user_phone,$open_id,$user_name,$res['from_id']);
        if($list)
        {
            $res['code'] = 1;
            $res['info'] = "登录成功";
            $res['data'] = $list;
        }else{
            $res['code'] = 2;
            $res['info'] = "您已经绑定过手机，该手机号无法绑定！";
            $res['data'] = $list;
        }
//        }else if($result == 1001){
//            $res['code'] = 2;
//            $res['info'] = "验证码已超时，请重新获取";
//            $res['data'] = array();
//        }else{
//            $res['code'] = 0;
//            $res['info'] = "验证码错误，请输入正确的验证码以后再进行登录";
//            $res['data'] = array();
//        }

        return json_encode($res);
    }
    /*
    * 获取预约详情
    * 接口地址：http://testxrtn.ggling.com/children/frontend/web/index.php?r=child/getbookinginfo
    * 参数：
    *      用户ID：user_id
    */
    public function actionGetbookinginfo()
    {

        /*
         * 接值
         */
        $user_id = Yii::$app->request->get('user_id');
        // $user_id=94;
        if(empty($user_id)){
            exit(json_encode(array('code'=>0,'info'=>'用户id不能为空')));
        }
        /*
         * 实例化用户表model层
         */
        $patientInfo = new TPatientInfo();
        /*
         * 实例化预约表model层
         */
        $bookingInfo = new TBookingInfo();
        /*
         * 实例化预约表model层
         */
        $sysUserInfo = new SysUserInfo();
        /*
         * 调用用户表model层中获取用户孩子列表的方法
         */
        $patient = $patientInfo->getUserPatientList($user_id);
        $subclinicInfo = new TSubclinicInfo();
        /*
         * 若不为空则成功，反之失败
         */
        if(!empty($patient))
        {
            $booking = new TBookingInfo();

            if(!empty($patient[0]['patient_id'])){
                $booking = $bookingInfo->getBookingInfo($patient[0]['patient_id']);
                $sysUserInfo = $sysUserInfo->getSysUserInfo($booking['doctor_id']);
                $subclinicInfo = $subclinicInfo ->getSubclinicInfo($sysUserInfo['subclinic_id']);
            }

            $retMap = array("patientInfo"=>$patient,"bookingInfo"=>$booking,'doctorInfo'=>$sysUserInfo,'subclinicInfo'=>$subclinicInfo);

            $res['code'] = 1;
            $res['info'] = "获取宝宝成功";
            $res['data'] = $retMap;
        }else{
            $res['code'] = 0;
            $res['info'] = "暂无数据";
            $res['data'] = array();
        }

        return json_encode($res);

    }
    /*
     * 验证手机验证码
     */
    public function actionCheckcode($user_phone,$code)
    {
        $time = time();
        /*
         * 实例化model层
         */
        $check = new UserCode();
        $list = $check->getList($user_phone);
        if($code == $list['rand_num'])
        {
            if($time-$list['create_time']>300)
            {
                return 1001;
            }else{
                return 1000;
            }
        }else{
            return 1002;
        }
    }
    
    /*
     * 问卷列表
     * 接口地址：http://testxrtn.ggling.com/children/frontend/web/index.php?r=child/getquestion
     * 
     */
    public function actionGetquestion()
    {
        
        /*
         * 实例化病症程度表model
         */
        $info = new InitHomeNursingInfo();
        /*
         * 调用查询列表
         */
        $array = $info->getList();
        $list = array();
        foreach($array as $k => $v)
        {
            $list[$v['type_id']]['id'] = $v['type_id'];
            $list[$v['type_id']]['tit'] = $v['type_name'];
//            $list[$v['type_id']]['qlist'][$k]['id'] = $v['nursing_id'];
//            $list[$v['type_id']]['qlist'][$k]['txt'] = $v['nursing_name'];
//            $list[$v['type_id']]['qlist'][$k]['nursing_value'] = $v['nursing_value'];
//            $list[$v['type_id']]['qlist'][$k]['sel'] = 'false';
        }
        foreach($array as $k => $v)
        {
            $qlist[$v['type_id']][$k]['id'] = $v['nursing_id'];
            $qlist[$v['type_id']][$k]['txt'] = $v['nursing_name'];
            $qlist[$v['type_id']][$k]['nursing_value'] = $v['nursing_value'];
            $qlist[$v['type_id']][$k]['sel'] = 'false';
        }
        $qlist = array_values($qlist);
        foreach($qlist as $k => $v)
        {
            $qlist[$k] = array_values($v);
        }
        $list = array_values($list);
        foreach($list as $k => $v)
        {
            $list[$k]['qlist'] = $qlist[$k];
        }

        return json_encode($list);
        
    }
    
    /*
     * 提交答案列表
     * 接口地址：http://testxrtn.ggling.com/children/frontend/web/index.php?r=child/answer
     */
    public function actionAnswer()
    {
        
        /*
         * 接值
         */
        $rel_id = Yii::$app->request->post('rel_id');
        $booking_id = Yii::$app->request->post('booking_id');
        $user_id = Yii::$app->request->post('user_id');
        $patient_id = Yii::$app->request->post('patient_id');
        $doctor_id = Yii::$app->request->post('doctor_id');
        $answer = Yii::$app->request->post('answer');
        $create_time = date('Y-m-d H:i:s',time());
        /*
         * 判断用户是否已经答题
         */
        $nersing = new TUserNersingRel();
        $list = $nersing->check($rel_id);
        if(empty($list))
        {
            if(is_array($answer))
            {
                foreach($answer as $k => $v)
                {
                    $answer[$k]['rel_id'] = $rel_id;
                    $answer[$k]['booking_id'] = $booking_id;
                    $answer[$k]['user_id'] = $user_id;
                    $answer[$k]['patient_id'] = $patient_id;
                    $answer[$k]['doctor_id'] = $doctor_id;
                    $answer[$k]['create_time'] = $create_time;
                }
                 /*
                 * 实例化答题表
                 */
                $trans = Yii::$app->db->beginTransaction();
                try{
                   foreach($answer as $k => $v)
                   {
                       $nersing1 = clone $nersing;
                       $result = $nersing1->setAnswer($v);
                       if(!$result)
                       {
                           $trans->rollback();
                           $res['code'] = 4;
                           $res['info'] = "提交失败，请重试";

                           return json_encode($res);
                       }
                   }
                   $res['code'] = 1;
                   $res['info'] = "提交成功";
                   $trans->commit();
                } catch (Exception $ex) {
                   $trans->rollback();
                   $res['code'] = 0;
                   $res['info'] = "提交失败，请重试";
                }
            }else{
                $res['code'] = 3;
                $res['info'] = "提交失败，请重试";
            }
        }else{
            $res['code'] = 2;
            $res['info'] = "您已提交过本次答题";
        }
        
        return json_encode($res);
        
    }
    
    /*
     * 病症程度列表
     * 接口地址：http://testxrtn.ggling.com/children/frontend/web/index.php?r=child/getdisease
     * 
     */
    public function actionGetdisease()
    {
        
        /*
         * 实例化病症程度表model
         */
        $info = new InitDiseaseInfo();
        /*
         * 调用查询列表
         */
        $array = $info->getList();
        $list = array();
        foreach($array as $k => $v)
        {
            $list[$v['type_id']]['id'] = $v['type_id'];
            $list[$v['type_id']]['tit'] = $v['type_name'];
	    $list[$v['type_id']]['is_main'] = $v['is_main'];
//            $list[$v['type_id']]['qlist'][$k]['id'] = $v['nursing_id'];
//            $list[$v['type_id']]['qlist'][$k]['txt'] = $v['nursing_name'];
//            $list[$v['type_id']]['qlist'][$k]['nursing_value'] = $v['nursing_value'];
//            $list[$v['type_id']]['qlist'][$k]['sel'] = 'false';
        }
        foreach($array as $k => $v)
        {
            $qlist[$v['type_id']][$k]['id'] = $v['desc_id'];
            $qlist[$v['type_id']][$k]['txt'] = $v['desc_name'];
            $qlist[$v['type_id']][$k]['disease_score'] = $v['disease_score'];
            $qlist[$v['type_id']][$k]['sel'] = 'false';
        }
        $qlist = array_values($qlist);
        foreach($qlist as $k => $v)
        {
            $qlist[$k] = array_values($v);
        }
        $list = array_values($list);
        foreach($list as $k => $v)
        {
            $list[$k]['qlist'] = $qlist[$k];
        }

        return json_encode($list);
        
    }
    

}
